package com.sec.android.app.myfiles.module.cloud;

import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.net.Uri;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.samsung.android.sdk.slinkcloud.CloudGatewayMediaStore;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.FolderSelectorBottomSheetActivity;
import com.sec.android.app.myfiles.feature.detailinfo.DetailsInfoMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsFileListAdapterImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.provider.DbTableInfo;
import com.sec.android.app.myfiles.provider.DbTableInfo.COLUMN_ID;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.listview.AbsListViewImp;
import com.sec.android.app.myfiles.widget.listview.FileListViewHolder;
import com.sec.android.app.myfiles.widget.listview.ListViewHolder;

import java.util.ArrayList;

public class CloudListAdapterImp extends AbsFileListAdapterImp {
    SparseBooleanArray mBindedViews = new SparseBooleanArray();

    public CloudListAdapterImp(Context context, NavigationInfo navigationInfo, AbsListViewImp listView, Cursor c, int flags) {
        super(context, navigationInfo, listView, c, flags);
    }

    @Override
    public void changeCursor(Cursor cursor) {
        mBindedViews.clear();
        super.changeCursor(cursor);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mNavigationInfo != null && mNavigationInfo.getCurFragment() != null && FolderSelectorBottomSheetActivity.mBottomSheetDragMap.get(mNavigationInfo.getCurFragment().getProcessId())) {
            if (mBindedViews.get(position)) {
                if (convertView == null) {
                    convertView = super.getView(position, convertView, parent);
                }
                if (position == 0 && convertView != null && convertView.getTag() != null && !((ListViewHolder) convertView.getTag()).getView(FileListViewHolder.NAME, TextView.class).getText().equals(mContext.getResources().getString(R.string.create_folder))) {
                    convertView = super.getView(position, convertView, parent);
                }
                return convertView;
            } else {
                mBindedViews.put(position, true);
            }
        }

        return super.getView(position, convertView, parent);
    }

    @Override
    protected void _bindView(Context context, ListViewHolder vh, android.view.View v, FileRecord record, int position) {
        super._bindView(context, vh, v, record, position);

        if (record instanceof CloudFileRecord) {
            CloudFileRecord cloudRecord = (CloudFileRecord) record;
            boolean isShowSync = false;
            if (UiUtils.isSyncing(record)) {
                isShowSync = true;
            }

            _bindProgressSync(context, vh, v, cloudRecord, isShowSync);

            if (cloudRecord.getFileId() == null && cloudRecord.getName().equals(context.getResources().getString(R.string.create_folder))) {
                _bindCreateFolderView(vh, v);
            }

            TextView textSize = vh.getView(FileListViewHolder.SIZE, TextView.class);
            if (record.isDirectory()) {
                boolean showHidden = PreferenceUtils.getShowHiddenFiles(context);
                textSize.setText(UiUtils.makeItemsString(context, record.getItemCount(showHidden)));
            }
        }
    }

    @Override
    protected void _bindContentDescription(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        if (UiUtils.isSyncing(record)) {
            v.setContentDescription(context.getResources().getString(R.string.folder) + ", " + record.getName() + ", "
                    + context.getResources().getString(R.string.tts_dimmed));
        } else {
            super._bindContentDescription(context, vh, v, record, position);
        }
    }

    @Override
    public Uri getUri() {
        Uri ret = super.getUri();
        if (mCurRecord instanceof CloudFileRecord) {
            String fileId = ((CloudFileRecord) mCurRecord).getFileId();
            int deviceId = ((CloudFileRecord) mCurRecord).getDeviceId();

            String uri = mTableInfo.getUri() + "?" + CloudProviderImp.DEVICE_ID_QUERY + "=" + deviceId + "&" + CloudProviderImp.FILE_ID_QUERY
                    + "=" + fileId;

            ret = Uri.parse(uri);
        }

        return ret;
    }

    @Override
    public String getSelection() {
        return null;
    }

    @Override
    public String[] getSelectionArgs() {
        return null;
    }

    @Override
    protected FileRecord _getFileRecord(Cursor cursor) {
        CloudFileRecord ret = null;

        if ((cursor != null) && (cursor.getCount() > 0)) {
            int sizeIndex = mTableInfo.getIndex(COLUMN_ID.SIZE);
            int dateIndex = mTableInfo.getIndex(COLUMN_ID.DATE);
            int typeIndex = mTableInfo.getIndex(COLUMN_ID.EXT);
            int nameIndex = mTableInfo.getIndex(COLUMN_ID.NAME);
            int mediaIdIndex = mTableInfo.getIndex(COLUMN_ID.MEDIA_ID);
            int fileIdIndex = mTableInfo.getIndex(COLUMN_ID.FILE_ID);
            int deviceIndex = mTableInfo.getIndex(COLUMN_ID.DEVICE_ID);
            int linkIndex = mTableInfo.getIndex(COLUMN_ID.ALTERNATIVE_LINK);
            int trashProcessingIndex = mTableInfo.getIndex(DbTableInfo.COLUMN_ID.TRASH_PROCESSING);

            try {
                int id = cursor.getInt(mediaIdIndex);
                String name = cursor.getString(nameIndex);
                long size = cursor.getLong(sizeIndex);
                long date = cursor.getLong(dateIndex) * 1000;
                String mimeType = cursor.getString(typeIndex);
                int fileType = MediaFile.getFileTypeForMimeType(mimeType);
                if (fileType == 0) {
                    fileType = MediaFile.getFileType(name, mContext);
                }
                String fileId = cursor.getString(fileIdIndex);
                int deviceId = cursor.getInt(deviceIndex);
                String googleDocsLink = null;
                int itemCount = 0;

                ArrayList<String> parentIds = new ArrayList<>();
                ArrayList<String> grandParentIds = ((CloudFileRecord) mCurRecord).getParentIds();
                if (grandParentIds != null) {
                    parentIds.addAll(grandParentIds);
                }
                parentIds.add(((CloudFileRecord) mCurRecord).getFileId());

                if ((mimeType != null) && !mimeType.isEmpty()) {
                    if (CloudGatewayMediaStore.FileBrowser.MIME_TYPE_DIR.equalsIgnoreCase(mimeType)) {
                        fileType = FileType.FOLDER;
                        int cntIndex = mTableInfo.getIndex(COLUMN_ID.ITEM_COUNT);
                        itemCount = cursor.getInt(cntIndex);
                    } else if (FileUtils.isGoogleDocs(mimeType)) {
                        googleDocsLink = cursor.getString(linkIndex);
                    }
                }
                String trashProcessing = cursor.getString(trashProcessingIndex);

                ret = new CloudFileRecord(id, deviceId, fileId, parentIds, mCurRecord.getFullPath(), name, size, date, fileType, 0, itemCount,
                        itemCount, googleDocsLink, mimeType, trashProcessing);
            } catch (IllegalStateException e) {
                Log.e(this, "IllegalStateException:" + e.toString());
            } catch (CursorIndexOutOfBoundsException e) {
                Log.e(this, "CursorIndexOutOfBoundsException:" + e.toString());
            }
        }

        return ret;
    }

    @Override
    public String getFilePath(Cursor cursor) {
        return null;
    }

    @Override
    public StorageType getStorageType() {
        return StorageType.Cloud;
    }

    @Override
    public Object[] getCreateFolderItem() {
        return new Object[]{0, mContext.getResources().getString(R.string.create_folder), 0, 0, 0, -1, null, 0, 0, 0, null};
    }

    @Override
    public void onLoadFinished(Cursor data) {
        if (!mCurRecord.isRoot() && !((CloudFileRecord) mCurRecord).isValidRecord(mContext)) {
            AbsMyFilesFragment curFragment = mNavigationInfo.getCurFragment();
            if (curFragment != null) {
                NavigationManager.getInstance(curFragment.getProcessId()).leave(mContext);
            }
        } else {
            super.onLoadFinished(data);
        }
    }

    @Override
    public int getEmptySubTextId() {
        int retId = -1;
        if ((FileRecord.CloudType.SamsungDrive == ((CloudFileRecord) mCurRecord).getCloudType())
                && (mCurRecord.isRoot())) {
            retId = (AppFeatures.IS_JPN) ? R.string.no_galaxy_drive_files : R.string.no_samsung_drive_files;
        } else {
            retId = super.getEmptySubTextId();
        }

        return retId;
    }

    @Override
    protected void _bindDefaultInfoView(Context context, ListViewHolder vh, FileRecord record) {
        super._bindDefaultInfoView(context, vh, record);
        TextView textSize = vh.getView(FileListViewHolder.SIZE, TextView.class);
        if (textSize != null) {
            textSize.setVisibility(View.VISIBLE);
            if (FileUtils.isGoogleDocs(record.getMimeType(context))) {
                textSize.setText(R.string.unknown);
            }
        }
    }
}
